<template>
  <div class="c_9">
    <div><button @click="goReset">重置默认商品</button></div>
    <div style="margin-top: 20px">
      <thead>
        <tr>
          <th>名称</th>
          <th>数量</th>
          <th>单价</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in infoList" :key="index">
          <th v-text="item.name"></th>
          <th>
            <button @click="goAdd(item, false)">-</button>{{ item.num
            }}<button @click="goAdd(item, true)">+</button>
          </th>
          <th v-text="item.price * item.num"></th>
          <th>
            <button @click="goDel(index)">删除</button>
          </th>
        </tr>
      </tbody>
      <tfoot>
        <tr>
          <th></th>
          <th></th>
          <th></th>
          <th v-text="'总价' + $total"></th>
        </tr>
      </tfoot>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { reactive, computed } from "vue";

interface ProInfo {
  name: string;
  num: number;
  price: number;
}

let infoList: ProInfo[] = reactive<Array<ProInfo>>([]);

const goReset = (): void => {
  const tempList = [
    { name: "衣服", num: 1, price: 100 },
    { name: "鞋子", num: 1, price: 30 },
    { name: "帽子", num: 1, price: 20 },
  ];
  infoList.splice(0);
  tempList.forEach((item) => {
    infoList.push(item);
  });
};

const goAdd = (obj: ProInfo, flag: boolean): void => {
  if (obj.num > 0) {
    if (flag) {
      obj.num++;
    } else {
      obj.num--;
    }
  } else if (obj.num == 0) {
    if (flag) {
      obj.num++;
    }
  }
};

const goDel = (index: number): void => {
  infoList.splice(index, 1);
};

const $total = computed(() => {
  return infoList.reduce((pre, next) => {
    return pre + next.num * next.price;
  }, 0);
});
</script>

<style scoped>
.c_9 {
  padding: 0;
}
thead tr th {
  width: 120px;
  height: 40px;
  border: 1px solid #666;
}
tbody tr th {
  width: 120px;
  height: 40px;
  border: 1px solid #666;
}
tfoot tr th {
  width: 120px;
  height: 40px;
  border: 1px solid #666;
}
</style>
